<template>
  <Dialog
    v-model="show"
    @confirm="handleSubmit"
    @close="close"
    :title="props?.data?.id ? $t('news.编辑消息') : $t('news.新增消息')"
    width="1000px"
  >
    <LangTabs v-model="lang" />
    <el-form :model="formData" label-width="120px" ref="formRef" :rules="rules">
      <el-form-item :label="$t('news.消息标题')" :prop="'title' + lang">
        <el-input v-model="formData['title' + lang]" :placeholder="$t('news.请输入')" />
      </el-form-item>
      <el-form-item :label="$t('news.内容')" :prop="'content' + lang">
        <EditorWang
          v-if="showEditorWang"
          v-model="formData['content' + lang]"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>
<script setup>
import { nextTick, ref, watch } from "vue";
import Dialog from "@/components/dialog.vue";
import EditorWang from "@/components/editorWang.vue";
import Api from "@/config/api/api";
import { setAttrLangs } from "@/i18n/tools";
import LangTabs from "@/components/langTabs.vue";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";

const { locale, t } = useI18n();
const lang = ref(locale.value);
const show = defineModel();
const showEditorWang = ref(true);
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["success"]);
watch(show, (val) => {
  if (val) {
    if (props?.data?.id) {
      formData.value = props.data;
      // setAttrLangs(formData.value, "title", props.data.title);
    }
  }
});
watch(
  () => lang.value,
  () => {
    showEditorWang.value = false;
    nextTick(() => {
      showEditorWang.value = true;
    });
  }
);
const formData = ref({});
const rules = ref({});
setAttrLangs(formData.value, "title", "");
setAttrLangs(formData.value, "content", "");
setAttrLangs(rules.value, "title", [
  { required: true, message: t('news.请输入'), trigger: "blur" },
]);
setAttrLangs(rules.value, "content", [
  { required: true, message: t('news.请输入消息内容'), trigger: "blur" },
]);
const formRef = ref();
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const params = {
        ...formData.value,
        id: props?.data?.id,
        toType: 10,
      };
      Api[props?.data?.id ? "editMessage" : "addMessage"](params).then(
        (res) => {
          const { status } = res;
          if (status === 200) {
            ElMessage.success(t('news.操作成功'));
            emit("success");
            close();
          }
        }
      );
    }
  });
};
const close = () => {
  setAttrLangs(formData.value, "title", "");
  setAttrLangs(formData.value, "content", "");
  formRef.value.resetFields();
  show.value = false;
  lang.value = locale.value;
};
</script>
